package explore.hxx.binarytree.self;

import explore.hxx.binarytree.dependence.TreeNode;

/**
 * 二叉树的最近公共祖先
 * @Author: waxijiang
 * @Date: 2021/6/7
 */
public class LowestCommonAncestor {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root.val == q.val || p.val == root.val) {
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left == null) {
            return right;
        }
        if (right == null) {
            return left;
        }
        return root;
    }
}
